import { Injectable } from '@angular/core';
import * as Nedb from "Nedb";

@Injectable()
export class NedbService {

  db: any

  constructor() {
    this.db = new Nedb({inMemoryOnly: false})
  }

  insert<T>(data: T): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.db.insert(data, (error) => {
        if (!error) {
          resolve(data)
        } else {
          reject(error)
        }
      });
    })
  }

  find<T>(data: T): Promise<T[]> {
    return new Promise<T[]>((resolve, reject) => {
      this.db.find({}, (error, docs:T[]) => {
        if (!error) {
          resolve(docs)
        } else {
          reject(error)
        }
      });
    })
  }
}
